package com.weatherstation.controller;

import com.weatherstation.entity.SensorData;
import com.weatherstation.service.SensorDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * 传感器数据控制器
 * 
 * @author WeatherStation Team
 */
@RestController
@RequestMapping("/sensors")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:5173"})
public class SensorDataController {
    
    private final SensorDataService sensorDataService;
    
    /**
     * 获取最新传感器数据
     */
    @GetMapping("/latest")
    public ResponseEntity<Map<String, Object>> getLatestData() {
        try {
            Optional<SensorData> latestData = sensorDataService.getLatestSensorData();
            
            if (latestData.isPresent()) {
                return ResponseEntity.ok(Map.of(
                    "success", true,
                    "data", latestData.get(),
                    "message", "获取最新数据成功"
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                    "success", false,
                    "data", null,
                    "message", "暂无传感器数据"
                ));
            }
        } catch (Exception e) {
            log.error("获取最新传感器数据失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取历史数据
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getHistoryData(
            @RequestParam(defaultValue = "24") int hours) {
        try {
            List<SensorData> historyData = sensorDataService.getRecentHoursData(hours);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", historyData,
                "count", historyData.size(),
                "hours", hours,
                "message", "获取历史数据成功"
            ));
        } catch (Exception e) {
            log.error("获取历史数据失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取历史数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取指定时间范围的数据
     */
    @GetMapping("/range")
    public ResponseEntity<Map<String, Object>> getDataByRange(
            @RequestParam String startTime,
            @RequestParam String endTime) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            
            List<SensorData> rangeData = sensorDataService.getSensorDataByTimeRange(start, end);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", rangeData,
                "count", rangeData.size(),
                "startTime", startTime,
                "endTime", endTime,
                "message", "获取指定范围数据成功"
            ));
        } catch (Exception e) {
            log.error("获取指定范围数据失败", e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "获取数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取最近N天的数据
     */
    @GetMapping("/recent-days")
    public ResponseEntity<Map<String, Object>> getRecentDaysData(
            @RequestParam(defaultValue = "7") int days) {
        try {
            List<SensorData> recentData = sensorDataService.getRecentDaysData(days);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", recentData,
                "count", recentData.size(),
                "days", days,
                "message", "获取最近" + days + "天数据成功"
            ));
        } catch (Exception e) {
            log.error("获取最近{}天数据失败", days, e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取每小时平均数据
     */
    @GetMapping("/hourly-average")
    public ResponseEntity<Map<String, Object>> getHourlyAverageData(
            @RequestParam(defaultValue = "24") int hours) {
        try {
            List<Map<String, Object>> hourlyData = sensorDataService.getHourlyAverageData(hours);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", hourlyData,
                "count", hourlyData.size(),
                "hours", hours,
                "message", "获取每小时平均数据成功"
            ));
        } catch (Exception e) {
            log.error("获取每小时平均数据失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
<<<<<<< HEAD
=======
     * 获取每小时数据（一天内的数据）
     * 使用专门的hourlyData方法，避免Object[]转换问题
     */
    @GetMapping("/hourly-data")
    public ResponseEntity<Map<String, Object>> getHourlyData(
            @RequestParam(defaultValue = "24") int hours) {
        try {
            if (hours > 24) {
                hours = 24; // 限制最多查询24小时
            }
            
            // 使用新的方法，直接返回Map列表
            List<Map<String, Object>> hourlyData = sensorDataService.getHourlyData(hours);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", hourlyData,
                "count", hourlyData.size(),
                "hours", hours,
                "message", "获取每小时数据成功"
            ));
        } catch (Exception e) {
            log.error("获取每小时数据失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
>>>>>>> 8812a9148e94551207e748afbba84869577bb3db
     * 获取每日统计数据
     */
    @GetMapping("/daily-statistics")
    public ResponseEntity<Map<String, Object>> getDailyStatistics(
            @RequestParam(defaultValue = "7") int days) {
        try {
            List<Map<String, Object>> dailyData = sensorDataService.getDailyStatistics(days);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", dailyData,
                "count", dailyData.size(),
                "days", days,
                "message", "获取每日统计数据成功"
            ));
        } catch (Exception e) {
            log.error("获取每日统计数据失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取数据统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getDataStatistics() {
        try {
            Map<String, Object> statistics = sensorDataService.getDataStatistics();
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", statistics,
                "message", "获取统计信息成功"
            ));
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取统计信息失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 添加传感器数据（用于测试或手动添加）
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addSensorData(
            @RequestBody Map<String, Object> requestData) {
        try {
            BigDecimal temperature = new BigDecimal(requestData.get("temperature").toString());
            BigDecimal humidity = new BigDecimal(requestData.get("humidity").toString());
            BigDecimal pressure = new BigDecimal(requestData.get("pressure").toString());
            Integer lightIntensity = Integer.valueOf(requestData.get("lightIntensity").toString());
            
            SensorData sensorData = sensorDataService.createSensorData(
                temperature, humidity, pressure, lightIntensity);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", sensorData,
                "message", "添加传感器数据成功"
            ));
        } catch (Exception e) {
            log.error("添加传感器数据失败", e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "添加数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 批量添加传感器数据
     */
    @PostMapping("/batch-add")
    public ResponseEntity<Map<String, Object>> batchAddSensorData(
            @RequestBody List<Map<String, Object>> requestDataList) {
        try {
            log.info("收到批量添加数据请求，数据量: {}", requestDataList.size());
            
            List<SensorData> sensorDataList = new ArrayList<>();
            
            for (Map<String, Object> data : requestDataList) {
                try {
                    BigDecimal temperature = new BigDecimal(data.get("temperature").toString());
                    BigDecimal humidity = new BigDecimal(data.get("humidity").toString());
                    BigDecimal pressure = new BigDecimal(data.get("pressure").toString());
                    Integer lightIntensity = Integer.valueOf(data.get("lightIntensity").toString());
                    
                    SensorData sensorData = new SensorData();
                    sensorData.setTemperature(temperature);
                    sensorData.setHumidity(humidity);
                    sensorData.setPressure(pressure);
                    sensorData.setLightIntensity(lightIntensity);
                    
                    // 如果提供了创建时间，则使用它
                    if (data.containsKey("createdAt")) {
                        try {
                            String createdAtStr = data.get("createdAt").toString();
                            DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
                            LocalDateTime createdAt = LocalDateTime.parse(createdAtStr, formatter);
                            sensorData.setCreatedAt(createdAt);
                        } catch (Exception e) {
                            log.warn("解析创建时间失败，使用当前时间: {}", e.getMessage());
                        }
                    }
                    
                    sensorDataList.add(sensorData);
                } catch (Exception e) {
                    log.warn("解析数据项失败，跳过: {}", e.getMessage());
                }
            }
            
            if (sensorDataList.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "没有有效的数据项"
                ));
            }
            
            List<SensorData> savedData = sensorDataService.saveBatchSensorData(sensorDataList);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", savedData,
                "count", savedData.size(),
                "message", "批量添加传感器数据成功"
            ));
        } catch (Exception e) {
            log.error("批量添加传感器数据失败", e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "批量添加数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取最近10条数据
     */
    @GetMapping("/latest-10")
    public ResponseEntity<Map<String, Object>> getLatest10Data() {
        try {
            List<SensorData> latest10 = sensorDataService.getLatest10Data();
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", latest10,
                "count", latest10.size(),
                "message", "获取最近10条数据成功"
            ));
        } catch (Exception e) {
            log.error("获取最近10条数据失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取数据失败: " + e.getMessage()
            ));
        }
    }
    /**
     * 获取历史数据（带分页）
     */
    @GetMapping("/history-paged")
    public ResponseEntity<Map<String, Object>> getHistoryDataPaged(
            @RequestParam(defaultValue = "24") int hours,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "100") int size) {
        try {
            // 先获取总数
            LocalDateTime startTime = LocalDateTime.now().minusHours(hours);
            LocalDateTime endTime = LocalDateTime.now();
            long totalCount = sensorDataService.getDataCountInTimeRange(startTime, endTime);
            
            // 分页获取数据
            List<SensorData> historyData = sensorDataService.getRecentHoursDataPaged(hours, page, size);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", historyData,
                "count", historyData.size(),
                "totalCount", totalCount,
                "hours", hours,
                "page", page,
                "size", size,
                "totalPages", Math.ceil((double) totalCount / size),
                "message", "获取历史数据成功"
            ));
        } catch (Exception e) {
            log.error("获取历史数据失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取历史数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取每月统计数据
     */
    @GetMapping("/monthly-statistics")
    public ResponseEntity<Map<String, Object>> getMonthlyStatistics(
            @RequestParam(defaultValue = "12") int months) {
        try {
            List<Map<String, Object>> monthlyData = sensorDataService.getMonthlyStatistics(months);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", monthlyData,
                "count", monthlyData.size(),
                "months", months,
                "message", "获取每月统计数据成功"
            ));
        } catch (Exception e) {
            log.error("获取每月统计数据失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 根据时间范围自动选择适当的数据聚合级别
     * 一天以内以小时为单位显示
     * 一个月以内以天为单位显示
     * 一年以内以月为单位显示(平均数据)
     */
    @GetMapping("/auto-aggregated")
    public ResponseEntity<Map<String, Object>> getAutoAggregatedData(
            @RequestParam(defaultValue = "24") int hours) {
        try {
            List<Map<String, Object>> resultData;
            String aggregationType;
            String timeRange;
            
            if (hours <= 24) {
                // 一天以内，按小时聚合
                resultData = sensorDataService.getHourlyAverageData(hours);
                aggregationType = "hourly";
                timeRange = hours + " hours";
            } else if (hours <= 720) { // 30天
                // 一个月以内，按天聚合
                int days = (int) Math.ceil(hours / 24.0);
                resultData = sensorDataService.getDailyStatistics(days);
                aggregationType = "daily";
                timeRange = days + " days";
            } else {
                // 一年以内，按月聚合
                int months = (int) Math.ceil(hours / 720.0); // 假设每月30天
                if (months > 12) months = 12; // 最多查询12个月
                resultData = sensorDataService.getMonthlyStatistics(months);
                aggregationType = "monthly";
                timeRange = months + " months";
            }
            
            // 记录日志
            log.info("自动聚合数据: 类型={}, 范围={}, 数据量={}", aggregationType, timeRange, resultData.size());
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", resultData,
                "count", resultData.size(),
                "aggregationType", aggregationType,
                "timeRange", timeRange,
                "message", "获取自动聚合数据成功"
            ));
        } catch (Exception e) {
            log.error("获取自动聚合数据失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取数据失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 测试数据库连接和数据
     */
    @GetMapping("/test-db")
    public ResponseEntity<Map<String, Object>> testDatabase() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 1. 检查数据库连接
            result.put("dbConnection", "成功");
            
            // 2. 获取数据总数
            Long totalCount = sensorDataService.getTotalCount();
            result.put("totalCount", totalCount);
            
            // 3. 获取最新数据
            Optional<SensorData> latestData = sensorDataService.getLatestSensorData();
            result.put("hasLatestData", latestData.isPresent());
            if (latestData.isPresent()) {
                result.put("latestData", latestData.get());
            }
            
            // 4. 获取最近1小时数据
            List<SensorData> recentHourData = sensorDataService.getRecentHoursData(1);
            result.put("recentHourCount", recentHourData.size());
            
            // 5. 获取最近1天数据
            List<SensorData> recentDayData = sensorDataService.getRecentHoursData(24);
            result.put("recentDayCount", recentDayData.size());
            
            // 6. 获取小时聚合数据
            List<Map<String, Object>> hourlyData = sensorDataService.getHourlyAverageData(24);
            result.put("hourlyDataCount", hourlyData.size());
            if (hourlyData.size() > 0) {
                result.put("hourlyDataSample", hourlyData.get(0));
            }
            
            // 7. 获取日聚合数据
            List<Map<String, Object>> dailyData = sensorDataService.getDailyStatistics(7);
            result.put("dailyDataCount", dailyData.size());
            if (dailyData.size() > 0) {
                result.put("dailyDataSample", dailyData.get(0));
            }
            
            // 8. 获取月聚合数据
            List<Map<String, Object>> monthlyData = sensorDataService.getMonthlyStatistics(12);
            result.put("monthlyDataCount", monthlyData.size());
            if (monthlyData.size() > 0) {
                result.put("monthlyDataSample", monthlyData.get(0));
            }
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "数据库测试成功",
                "data", result
            ));
        } catch (Exception e) {
            log.error("数据库测试失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "数据库测试失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 测试接口 - 创建一条测试数据并返回
     */
    @GetMapping("/test-create")
    public ResponseEntity<Map<String, Object>> testCreateData() {
        try {
            // 创建一条测试数据
            BigDecimal temperature = new BigDecimal("25.5");
            BigDecimal humidity = new BigDecimal("60.0");
            BigDecimal pressure = new BigDecimal("101325");
            Integer lightIntensity = 500;
            
            SensorData testData = new SensorData(temperature, humidity, pressure, lightIntensity);
            SensorData savedData = sensorDataService.saveSensorData(testData);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "测试数据创建成功",
                "data", savedData
            ));
        } catch (Exception e) {
            log.error("测试数据创建失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "测试数据创建失败: " + e.getMessage(),
                "error", e.toString(),
                "stackTrace", e.getStackTrace()
            ));
        }
    }
}